﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using HtmlAgilityPack;

namespace MaximServices.Services.MottoCrawl
{
    public class BaiduBaikeCrawl : IBaikeCrawl
    {
        /// <summary>
        /// 百度百科搜索的地址
        /// </summary>
        private static string BAIKE_SEARCH_WORD_URL = "https://baike.baidu.com/search/word";

        public CrawlResult MatchMotto(string keyword)
        {
            //模拟提交百度表单，检查词条是否存在，如果不存在，直接返回
            //如果有多条命中，解析多条内容，将地址抓取回来
            //如果唯一命中，将页面地址抓取回来
            var postContent = $"{BAIKE_SEARCH_WORD_URL}?word={ keyword }";

            var crawlResult = new CrawlResult(keyword);

            try
            {
                var redirectUrl = string.Empty;

                var content = Common.HttpHelper.GetHTMLByURL(postContent, out redirectUrl);

                WhatPage(redirectUrl, content, crawlResult);
            }
            catch (Exception ex)
            {
                crawlResult.Error = ex.Message;
            }

            return crawlResult;
        }

        /// <summary>
        /// 判断内容是哪个页面
        /// </summary>
        /// <returns></returns>
        private void WhatPage(string pageUrl, string content, CrawlResult crawlResult)
        {
            HtmlDocument doc = new HtmlDocument();

            doc.LoadHtml(content);

            var node = doc.DocumentNode.SelectSingleNode("//div[@class=\"content-wrapper\"]");

            //看一下是否是详情页
            if (node != null)
            {
                //确认一下是否是详情页
                node = doc.DocumentNode.SelectSingleNode("//div[@class=\"main-content\"]");

                if (node != null)
                {
                    //确实是详情页了， 检查是唯一匹配还是多个匹配
                    node = doc.DocumentNode.SelectSingleNode("//ul[@class=\"polysemantList-wrapper cmn-clearfix\"]");

                    if (node != null)
                    {
                        FindSameNameNode(node, pageUrl, crawlResult);
                    }
                    else
                    {
                        crawlResult.FoundOne(crawlResult.KeyWord, pageUrl);
                    }
                }
            }

            if (crawlResult.MatchPageType == null)
            {
                crawlResult.NotFound();
            }
        }

        /// <summary>
        /// 解析同名的节点
        /// </summary>
        /// <param name="node"></param>
        /// <param name="crawlResult"></param>
        private void FindSameNameNode(HtmlNode node, string pageUrl, CrawlResult crawlResult)
        {
            var sameNode = new List<MottoLite>();

            var liNodes = node.SelectNodes("li[@class=\"item\"]");

            foreach (var li in liNodes)
            {
                //查找当前选中的节点
                var subNode = li.SelectSingleNode("span[@class=\"selected\"]");

                if (subNode != null)
                {
                    sameNode.Add(new MottoLite()
                    {
                        Title = subNode.InnerText,
                        BaiKeUrl = pageUrl
                    });
                }
                else
                {
                    subNode = li.SelectSingleNode("a");

                    if (subNode != null && subNode.HasAttributes)
                    {
                        sameNode.Add(new MottoLite()
                        {
                            Title = subNode.InnerText,
                            BaiKeUrl = "https://baike.baidu.com" + subNode.Attributes["href"].Value
                        });
                    }
                }
            }

            crawlResult.FoundMore(sameNode);
        }
    }
}
